<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class Post extends Model
{
    // 指定表名
    protected $table = 'posts';

    // 允许批量赋值的字段
    protected $fillable = ['title', 'content', 'user_id'];

    // 禁止批量赋值的字段
    protected $guarded = [];

    // ElasticSearch 搜索支持
    // use Searchable;

    // 定义索引里面的type[表]
    public function searchableAs()
    {
        return 'post';
    }

    // 定义哪些字段需要搜索
    public function toSearchableArray()
    {
        return [
            'title' => $this->title,
            'content' => $this->content,
        ];
    }

    // 关联user模型
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    // 关联评论模型 [一对多] [以评论模型为角度]
    public function comments()
    {
        return $this->hasMany(Comment::class, 'post_id', 'id')->latest();
    }

    // 关联赞模型[用户] [返回关联模型]
    public function zan($user_id)
    {
        return $this->hasOne(Zan::class, 'post_id', 'id')->where('user_id', $user_id);
    }
    
    // 赞计数
    public function zans()
    {
        return $this->hasMany(Zan::class, 'post_id', 'id');
    }

    // 找到文章所属的topics
    public function PostTopics()
    {
        return $this->hasMany(PostTopic::class, 'post_id', 'id');
    }

    // 属于某个作者的文章
    public function scopeAuthorBy(Builder $query, $user_id)
    {
        return $query->where('user_id', $user_id);
    }

    // 不属于专题的文章
    public function scopeNotTopic(Builder $query, $topic_id)
    {
        return $query->doesntHave(
            'PostTopics',
            'and',
            function (Builder $queryTopics) use ($topic_id) {
                // 使用关联的topics模型查询, 查询到的结果排除
                $queryTopics->where('topic_id', $topic_id);
            }
        );
    }

    // 全局scope
    protected static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub

        static::addGlobalScope('avaiable', function (Builder $builder) {
            // 非审核拒绝文章
            $builder->whereIn('status', [0, 1]);
        });
    }
}
